package com.java.message.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author 浮生光
 * @create 2021/9/11 15:41
 */
@Controller
public class IndexController {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @RequestMapping(value = {"/","/index"},method = RequestMethod.GET)
    public String index(){
        return "index";
    }

    @ResponseBody
    @RequestMapping(value = "/sendmessage",method = RequestMethod.GET)
    public String sendmessage(){
        String userId = "1";
        String code = getCode();
        String rediskey = "VERIFATIONCODE:CODE:"+userId;
        redisTemplate.opsForValue().set(rediskey,code,300, TimeUnit.SECONDS);
        boolean isSuccess = send(code);
        if(isSuccess){
            return "success";
        }else {
            return "fail";
        }

    }

    private boolean send(String code){
        String msg="验证码为："+code+"，验证码有效期5分钟，请及时验证";
        System.out.println(msg);
        return true;
    }

    private static String getCode(){
        Random random = new Random();
        String result = "";
        for (int i=0;i<6;i++){
            result+=random.nextInt(10);
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/checkCode",method = RequestMethod.GET)
    public String checkCode(@RequestParam("inputCode") String inputCode){
        String userId="1";
        //设置redis的key，这里设置为项目名:使用的字段:用户Id
        String redisKey="VERIFATIONCODE:CODE:"+userId;
        String realCode= (String) redisTemplate.opsForValue().get(redisKey);
        if (realCode!=null&&realCode.equals(inputCode)){
            return "success";
        }else {
            return "fail";
        }
    }








}
